package com.atguigu.chapter10;

import com.atguigu.bean.LoginEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/23 14:57
 */
public class Flink01_Login {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        // 创建WatermarkStrategy
        WatermarkStrategy<LoginEvent> wms = WatermarkStrategy
            .<LoginEvent>forBoundedOutOfOrderness(Duration.ofSeconds(20))
            .withTimestampAssigner(new SerializableTimestampAssigner<LoginEvent>() {
                @Override
                public long extractTimestamp(LoginEvent element, long recordTimestamp) {
                    return element.getEventTime();
                }
            });
        KeyedStream<LoginEvent, Long> loginKS = env
            .readTextFile("input/LoginLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new LoginEvent(Long.valueOf(data[0]),
                                      data[1],
                                      data[2],
                                      Long.parseLong(data[3]) * 1000L);
            })
            .assignTimestampsAndWatermarks(wms)
            .keyBy(LoginEvent::getUserId);
        
        // 1. 定义模式
        // 紧挨着两个fail, 并且在2s以内
        Pattern<LoginEvent, LoginEvent> pattern = Pattern
            .<LoginEvent>begin("firstFail")
            .where(new SimpleCondition<LoginEvent>() {
                @Override
                public boolean filter(LoginEvent value) throws Exception {
                    return "fail".equals(value.getEventType());
                }
            })
            .next("secondFail")
            .where(new SimpleCondition<LoginEvent>() {
                @Override
                public boolean filter(LoginEvent value) throws Exception {
                    return "fail".equals(value.getEventType());
                }
            })
            .within(Time.milliseconds(2001));
        
        // 2. 把模式应用到流上
        PatternStream<LoginEvent> ps = CEP.pattern(loginKS, pattern);
        // 3. 取出数据
        SingleOutputStreamOperator<String> normal = ps.select(
            new OutputTag<String>("异常") {},
            new PatternTimeoutFunction<LoginEvent, String>() {
                @Override
                public String timeout(Map<String, List<LoginEvent>> pattern, long timeoutTimestamp) throws Exception {
                    return null;
                }
            },
            new PatternSelectFunction<LoginEvent, String>() {
                @Override
                public String select(Map<String, List<LoginEvent>> pattern) throws Exception {
                    LoginEvent f1 = pattern.get("firstFail").get(0);
                    LoginEvent f2 = pattern.get("secondFail").get(0);
                    return f1.getUserId() + "在恶意登录";
                }
            }
        );
    
        normal.print();
    
        env.execute();
        
    }
}
